package com.oldroid.apps.getit.ui.adapter;

import java.io.File;
import java.net.URLConnection;
import java.sql.Date;

import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.oldroid.apps.getit.R;
import com.oldroid.apps.getit.provider.DownloadsContract.Downloads;
import com.oldroid.apps.getit.provider.DownloadsContract.Downloads_Tags;
import com.oldroid.apps.getit.provider.DownloadsContract.Tags;

public class DownloadsAdapter extends CursorAdapter {
	private static final String TAG = "DownloadsAdapter";
	private Cursor cursor;
	private Cursor tagCursor;
	private ViewHolder holder;
	private Context mContext;
	private ContentResolver mContentResolver;
	/**
	 * Determines if the tags are to be shown in the UI. By default tags are
	 * hidden.
	 */
	public boolean showTags = true;

	public DownloadsAdapter(Context context, Cursor c, Cursor tagCursor) {
		super(context, c, true);
		this.mContext = context;
		mContentResolver = context.getContentResolver();
		cursor = c;
		this.tagCursor = tagCursor;
		this.getItem(0);
	}

	// static class ViewHolder {
	class ViewHolder {
		public TextView filenameTextView;
		public TextView fileuriTextView;
		public TextView filesizeTextView;
		public TextView timestampTextView;
		public TextView taggsTextView;
		public CompoundButton starredImageView;
	}

	@Override
	public View newView(Context context, Cursor c, ViewGroup parent) {
		LayoutInflater inflater = LayoutInflater.from(context);
		View v = inflater.inflate(R.layout.downloads_item_row, parent, false);

		return v;
	}

	/**
	 * Prepares the view holder with the appropriate views.
	 * 
	 * @param v
	 */
	private void prepViewHolder(View v) {
		holder = new ViewHolder();
		holder.filenameTextView = (TextView) v.findViewById(R.id.downloads_filename);
		holder.fileuriTextView = (TextView) v.findViewById(R.id.downloads_fileuri);
		holder.filesizeTextView = (TextView) v.findViewById(R.id.downloads_filesize);
		holder.timestampTextView = (TextView) v.findViewById(R.id.downloads_created);
		holder.taggsTextView = (TextView) v.findViewById(R.id.downloads_tags);
		holder.starredImageView = (CompoundButton) v.findViewById(R.id.downloads_starred);
	}

	@Override
	public void bindView(View view, final Context context, final Cursor cursor) {
		// IT TURNS OUT WE DON'E NEED TO USE THE VIEW HOLDER PATTERN
		// Since CursorAdapter does it by default
		// needs to be fixed later
		prepViewHolder(view);
		final long id = cursor.getInt(Downloads.COLUMN_INDEX_ID);
		String fileName = cursor.getString(Downloads.COLUMN_INDEX_FILENAME);
		String fileUri = cursor.getString(Downloads.COLUMN_INDEX_URI);
		int end = fileUri.indexOf(fileName);
		fileUri = fileUri.substring(0, end);
		String fileSize = cursor.getString(Downloads.COLUMN_INDEX_TOTAL_BYTES);
		double MEGA_BYTE = 1024.0 * 1024.0;
		double KILO_BYTE = 1024.0;
		if (Double.parseDouble(fileSize) > MEGA_BYTE) {
			fileSize = String.format("%2.2f MB", Integer.parseInt(fileSize) / MEGA_BYTE);
		} else if (Double.parseDouble(fileSize) >= 900) {
			fileSize = String.format("%2.2f KB", Integer.parseInt(fileSize) / KILO_BYTE);
		} else if (Double.parseDouble(fileSize) > 0) {
			fileSize = String.format("%d bytes", Integer.parseInt(fileSize));
		} else
			fileSize = "0 byte";
		Date date = new Date(Long.parseLong(cursor.getString(Downloads.COLUMN_INDEX_CREATED)));
		String timeStamp = "" + (date.getMonth() + 1) + "/" + (date.getDate()) + "/" + (date.getYear() + 1900);
		holder.starredImageView.setChecked(cursor.getInt(Downloads.COLUMN_INDEX_STARRED) != 0);
		holder.starredImageView.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				final ContentValues values = new ContentValues();
				values.put(Downloads.STARRED, isChecked ? 1 : 0);
				mContentResolver.update(Downloads.buildDownloadsUri(id), values, null, null);

			}
		});

		// holder.filenameTextView.setText(position + ")" + fileName);
		holder.filenameTextView.setText(fileName);
		holder.fileuriTextView.setText(fileUri);
		holder.filesizeTextView.setText(fileSize);
		holder.timestampTextView.setText(timeStamp);

		// /**
		// * Show the tags if instructed to do so
		// */
		// if (showTags) {
		// new AsyncTask<Void, Void, String>() {
		//
		// @Override
		// protected String doInBackground(Void... params) {
		StringBuilder sb = new StringBuilder();
		sb.append("#: ");
		// the cursor contains all tags related to the current file
		Cursor downloads_tags_cursor = mContentResolver.query(Downloads_Tags.CONTENT_URI, null,
				Downloads_Tags.DOWNLOADS_ID + "=?", new String[] { "" + id }, null);
		while (downloads_tags_cursor.moveToNext()) {
			int tagID = downloads_tags_cursor.getInt(Downloads_Tags.COLUMN_INDEX_TAG_ID);
			final Cursor tagCursor = mContentResolver.query(Tags.CONTENT_URI, null, Tags._ID + "=?",
					new String[] { String.valueOf(tagID) }, null);
			if (tagCursor.moveToFirst())
				sb.append(tagCursor.getString(Tags.COLUMN_INDEX_TAG));
			if (downloads_tags_cursor.isLast())
				break;
			else
				sb.append(", ");

		}
		holder.taggsTextView.setText(sb);
		holder.taggsTextView.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// display the TagAdder dialog
				Toast.makeText(mContext, "Multiple Tags will be coming soon", Toast.LENGTH_SHORT).show();
			}
		});
		// return sb.toString();
		// }
		//
		// @Override
		// protected void onPostExecute(String result) {
		// if(result==null){
		// throw new IllegalArgumentException("can't be null");
		// }else{
		// Log.v(TAG, result);
		// holder.taggsTextView.setText(result);
		// }
		// }
		//
		//
		// }.execute();
		/**
		 * Add an on click listener so that we open the file when it's filename
		 * textview is clicked upon
		 */
		holder.filenameTextView.setOnClickListener(new OnClickListener() {

			final String name = cursor.getString(Downloads.COLUMN_INDEX_FILENAME);
			final String path = cursor.getString(Downloads.COLUMN_INDEX_URI);

			public void onClick(View v) {
				// TODO Auto-generated method stub

				File fp = new File(path);

				if (!fp.exists()) {
					return;
				}

				try {
					Intent i = new Intent();
					i.setAction(Intent.ACTION_VIEW);
					i.setDataAndType(Uri.fromFile(fp), URLConnection.guessContentTypeFromName(fp.getName()));
					Log.v(TAG, "Clicked text view. Filename = " + name);
					// Toast.makeText(mContext, "Filename = " + name + " Pos = "
					// + cursor.getPosition(),Toast.LENGTH_SHORT).show();
					// Toast.makeText(mContext, "NewCurPos = "
					// +cursor.getPosition() + ". Name = " +
					// cursor.getString(Downloads.COLUMN_INDEX_FILENAME),
					// Toast.LENGTH_SHORT).show();
					mContext.startActivity(i);

				} catch (ActivityNotFoundException e) {
					Toast.makeText(mContext, "No program capable of opening that file was found.", Toast.LENGTH_SHORT)
							.show();
				}

			}
		});

	}

	private String getTags(long downloadID) {

		String tags = "";

		Cursor c = mContentResolver.query(Downloads_Tags.CONTENT_URI, null, Downloads_Tags.DOWNLOADS_ID + "=?",
				new String[] { String.valueOf(downloadID) }, null);

		if (c.moveToFirst()) {// given download id has a tag stored for it.
			// pull off the tag.

			int tagID = c.getInt(Downloads_Tags.COLUMN_INDEX_TAG_ID);

			Cursor tagCursor = mContentResolver.query(Tags.CONTENT_URI, null, Tags._ID + "=?",
					new String[] { String.valueOf(tagID) }, null);

			// if (tagCursor.moveToFirst()) { // get the tag name for the given
			// tag
			// // id
			//
			// tags = tagCursor.getString(Tags.COLUMN_INDEX_TAG);
			//
			// }

			while (tagCursor.moveToNext()) {
				tags += tagCursor.getString(Tags.COLUMN_INDEX_TAG);
				if (!tagCursor.isLast()) {
					tags += ", ";
				}
			}
		}

		return "#: " + tags;
	}

	// @Override
	// public View getView(int arg0, View arg1, ViewGroup arg2) {
	// // TODO Auto-generated method stub
	// return super.getView(arg0, arg1, arg2);
	// }

}
